package backend.opt;

import backend.Instruction.*;
import backend.Register.RISCVreg;
import backend.component.RISCVblock;
import backend.component.RISCVfunction;
import backend.Instruction.RISCVinst;
import backend.component.RISCVmodule;
import backend.component.RISCVimm;
import backend.Instruction.RISCVj;
import backend.Register.RISCVoperand;
import backend.Register.initReg;
import backend.Register.physicalReg;
import Utils.Pair;

import java.util.*;

import static backend.Register.initReg.phyRegs;
import static backend.Register.initReg.phyfRegs;

public class RISCVOptimize {
    // 存储模块信息
    private final RISCVmodule module;
    // 块到指令列表的映射
    private final HashMap<RISCVblock, LinkedList<RISCVinst>> blockInstr = new HashMap<>();
    // 函数到块列表的映射
    private final HashMap<RISCVfunction, LinkedList<RISCVblock>> funcBlock = new HashMap<>();
    // 存储块到目标块的映射（用于跳转优化）
    private final HashMap<RISCVblock, RISCVblock> tarBlock = new HashMap<>();

    // 构造函数：初始化优化器
    public RISCVOptimize(RISCVmodule module) {
        this.module = module;
        initializeDataStructures();
    }

    // 初始化数据结构：建立函数、块和指令的映射关系
    private void initializeDataStructures() {
        for (RISCVfunction function : module.getFunctions()) {
            for (RISCVblock block : function.getBlocks()) {
                blockInstr.put(block, block.getInstructionlist());
            }
            funcBlock.put(function, function.getBlocks());
        }
    }

    // 执行所有优化步骤的入口方法
    public void run() {
        deleteUselessMove();    // 删除无用移动指令
        tryUseMV();             //尝试多使用move
        deleteUselessLi();       // 删除无用立即数加载
        changeReg2Zero();        // 使用零寄存器优化
        deleteUselessAdd1();     // 删除无用加法指令
        reOrderBlock();          // 重排基本块顺序
        peepHole();              // 窥孔优化
        deleteUnUsedBlock();     // 删除未使用的基本块
    }

    // 删除无用的move指令（如 move a, a）
    public void deleteUselessMove() {
        for (RISCVblock block : blockInstr.keySet()) {
            ArrayList<RISCVinst> redundantMoves = new ArrayList<>();

            // 遍历块中所有指令，找出目标寄存器与源寄存器相同的move指令
            for (RISCVinst inst : block.getInstructionlist()) {
                if (inst instanceof RISCVmove moveInst &&
                        moveInst.getSrc().equals(moveInst.getDst())) {
                    redundantMoves.add(moveInst);
                }
            }

            // 删除标记的冗余指令
            removeInstructions(block, redundantMoves);
        }
    }

    private void tryUseMV(){
        for (RISCVblock block : blockInstr.keySet()) {
            //ArrayList<RISCVinst> needtochange = new ArrayList<>();
            ArrayList<RISCVinst> deletelist = new ArrayList<>();
            ArrayList<Pair<RISCVinst, RISCVinst>> insertlist = new ArrayList<>();

            for (int i = 0; i < block.getInstructionlist().size();i++) {
                RISCVinst inst = block.getInstructionlist().get(i);
                if(inst instanceof RISCVbinary riscVbinary){
                    if(riscVbinary.getType().equals("xor") && riscVbinary.getSrc2().equals(initReg.ZERO)){
                        //System.out.println("xor zero");
                        RISCVmove riscVmove = new RISCVmove(Arrays.asList(riscVbinary.getDst(),riscVbinary.getSrc1()));
                        insertlist.add(new Pair<>(riscVmove, riscVbinary));
                        deletelist.add(riscVbinary);
                    }
                    else if(riscVbinary.getType().equals("xor") && riscVbinary.getSrc2() instanceof RISCVimm riscVimm && riscVimm.getImm() == 0){
                        //System.out.println("xori 0");
                        RISCVmove riscVmove = new RISCVmove(Arrays.asList(riscVbinary.getDst(),riscVbinary.getSrc1()));
                        insertlist.add(new Pair<>(riscVmove, riscVbinary));
                        deletelist.add(riscVbinary);
                    }
                    if(riscVbinary.getType().equals("or") && riscVbinary.getSrc2().equals(initReg.ZERO)){
                        //System.out.println("ori zero");
                        RISCVmove riscVmove = new RISCVmove(Arrays.asList(riscVbinary.getDst(),riscVbinary.getSrc1()));
                        insertlist.add(new Pair<>(riscVmove, riscVbinary));
                        deletelist.add(riscVbinary);
                    }
                    else if(riscVbinary.getType().equals("or") && riscVbinary.getSrc2() instanceof RISCVimm riscVimm && riscVimm.getImm() == 0){
                        //System.out.println("ori 0");
                        RISCVmove riscVmove = new RISCVmove(Arrays.asList(riscVbinary.getDst(),riscVbinary.getSrc1()));
                        insertlist.add(new Pair<>(riscVmove, riscVbinary));
                        deletelist.add(riscVbinary);
                    }
                    if(riscVbinary.getType().equals("xor") && riscVbinary.getSrc2().equals(initReg.ZERO)){
                        //System.out.println("xor zero");
                        RISCVmove riscVmove = new RISCVmove(Arrays.asList(riscVbinary.getDst(),riscVbinary.getSrc1()));
                        insertlist.add(new Pair<>(riscVmove, riscVbinary));
                        deletelist.add(riscVbinary);
                    }
                    else if(riscVbinary.getType().equals("xor") && riscVbinary.getSrc2() instanceof RISCVimm riscVimm && riscVimm.getImm() == 0){
                        //System.out.println("xori 0");
                        RISCVmove riscVmove = new RISCVmove(Arrays.asList(riscVbinary.getDst(),riscVbinary.getSrc1()));
                        insertlist.add(new Pair<>(riscVmove, riscVbinary));
                        deletelist.add(riscVbinary);
                    }
                    if(riscVbinary.getType().equals("and") && (riscVbinary.getSrc2().equals(initReg.ZERO) || riscVbinary.getSrc1().equals(initReg.ZERO))){
                        //System.out.println("and zero");
                        RISCVmove riscVmove = new RISCVmove(Arrays.asList(riscVbinary.getDst(),initReg.ZERO));
                        insertlist.add(new Pair<>(riscVmove, riscVbinary));
                        deletelist.add(riscVbinary);
                    }
                    else if(riscVbinary.getType().equals("and") && ((riscVbinary.getSrc2() instanceof RISCVimm riscVimm && riscVimm.getImm() == 0||(riscVbinary.getSrc1() instanceof RISCVimm riscVimm1 && riscVimm1.getImm() == 0)))){
                        //System.out.println("andi 0");
                        RISCVmove riscVmove = new RISCVmove(Arrays.asList(riscVbinary.getDst(),initReg.ZERO));
                        insertlist.add(new Pair<>(riscVmove, riscVbinary));
                        deletelist.add(riscVbinary);
                    }
                }
            }

            for(Pair<RISCVinst, RISCVinst> p:insertlist){
                block.insertBefore(p.getSecond(),p.getFirst());
            }
            // 删除标记的冗余指令
            removeInstructions(block, deletelist);
        }
    }

    // 删除无用的立即数加载指令
    private void deleteUselessLi() {
        for (RISCVblock block : blockInstr.keySet()) {
            //需要变化的指令
            List<RISCVinst> redundantLoads = new ArrayList<>();
            Map<RISCVbinary, Integer> binariesToUpdate = new HashMap<>();

            LinkedList<RISCVinst> instructions = block.getInstructionlist();
            // 遍历指令序列（除最后一条）
            for (int i = 0; i < instructions.size() - 1; i++) {
                RISCVinst current = instructions.get(i);
                if(!(current instanceof RISCVmove)){
                    continue;
                }
                RISCVinst next = instructions.get(i + 1);

                for(int j = i + 1; j < instructions.size(); j++) {
                    next = instructions.get(j);
                    if(next instanceof RISCVmove){
                        next = null;
                        break;
                    }
                    if(next instanceof RISCVbinary){
                        break;
                    }
                    if(next.getRegUse().contains(((RISCVmove) current).getDst())) {
                        next = null;
                        break;
                    }
                    next = null;
                }
                if(next == null){
                    continue;
                }
                // 处理可能的立即数加载优化场景
                processLiInstruction(block, current, next, redundantLoads, binariesToUpdate);
            }

            // 删除冗余加载指令
            removeInstructions(block, redundantLoads);
            // 更新需要修改的二元指令
            updateBinaryInstructions(binariesToUpdate);
        }
    }

    // 处理立即数加载指令的优化机会 此处只是特别优化 li a 1000  add a a b 类似的
    private void processLiInstruction(RISCVblock block, RISCVinst current, RISCVinst next,
                                      List<RISCVinst> redundantLoads,
                                      Map<RISCVbinary, Integer> binariesToUpdate) {
        // 只处理移动指令（即li指令）
        if (!(current instanceof RISCVmove moveInst)) return;
        if (!(moveInst.getSrc() instanceof RISCVimm immSrc)) return;

        int immValue = immSrc.getImm();
        // 检查立即数是否在有效范围内（-2048到2047）
        if (!isValidImmediate(immValue)) return;
        // 跳过特殊寄存器
        if (((physicalReg) moveInst.getDst()).isSReg()) return;
        // 只处理后跟算术指令的情况
        if (!(next instanceof RISCVbinary binaryNext)) return;

        String opType = binaryNext.getType();
        RISCVoperand dstReg = moveInst.getDst();

        // 处理加法操作（add/addw）
        if (isAddOperation(opType)) {
            if (binaryNext.getSrc2().equals(dstReg)) {
                // 目标寄存器在第二个操作数位置
                //删除 的时候需要注意以下，可能 li 赋值 的寄存器后续还有使用的可能性

                if (binaryNext.getDst().equals(dstReg) || isTReg(dstReg)) {
                    handleLiAddorSubCase(moveInst, binaryNext, immValue, redundantLoads, binariesToUpdate);
                }
            }
            else if (binaryNext.getSrc1().equals(dstReg)) {
                // 目标寄存器在第一个操作数位置，交换操作数

                if (binaryNext.getDst().equals(dstReg) || isTReg(dstReg)) {
                    swapOperands(binaryNext);
                    handleLiAddorSubCase(moveInst, binaryNext, immValue, redundantLoads, binariesToUpdate);
                }
            }
        }
        // 处理减法操作（subw）
        else if ("subw".equals(opType) && binaryNext.getSrc2().equals(dstReg)) {
            if (binaryNext.getDst().equals(dstReg) || isTReg(dstReg)) {
                handleLiAddorSubCase(moveInst, binaryNext, immValue, redundantLoads, binariesToUpdate);
            }
        }
    }

    private boolean isTReg(RISCVoperand dstReg) {
        return false ;/*dstReg.equals(phyRegs.get(5)) || dstReg.equals(phyRegs.get(6)) || dstReg.equals(phyRegs.get(7)) || dstReg.equals(phyRegs.get(28)) || dstReg.equals(phyRegs.get(29)) || dstReg.equals(phyRegs.get(30)) || dstReg.equals(phyRegs.get(31))
        ||dstReg.equals(phyfRegs.get(0)) || dstReg.equals(phyfRegs.get(1))||dstReg.equals(phyfRegs.get(2)) || dstReg.equals(phyfRegs.get(3))|| dstReg.equals(phyfRegs.get(4))
                || dstReg.equals(phyfRegs.get(5)) || dstReg.equals(phyfRegs.get(6)) || dstReg.equals(phyfRegs.get(7)) || dstReg.equals(phyfRegs.get(28)) || dstReg.equals(phyfRegs.get(29)) || dstReg.equals(phyfRegs.get(30)) || dstReg.equals(phyfRegs.get(31));*/
    }

    //检查可不可以简化代码，减少 li指令 ，如果寄存器是 自己改变或者修改自己，或者使用 t0寄存器就不存在问题
    private boolean isCanChange(RISCVoperand a,RISCVoperand b){
        return a.equals(b) || b.equals(phyRegs.get(5));
    }


    // 检查立即数是否在合法范围内
    private boolean isValidImmediate(int value) {
        return value >= -2048 && value <= 2047;
    }

    // 判断是否为加法操作
    private boolean isAddOperation(String type) {
        return "add".equals(type) || "addw".equals(type);
    }

    // 处理加法 减法优化情况
    private void handleLiAddorSubCase(RISCVmove moveInst, RISCVbinary binary,
                                 int immValue, List<RISCVinst> redundantLoads,
                                 Map<RISCVbinary, Integer> binariesToUpdate) {
        redundantLoads.add(moveInst);       // 标记加载指令为冗余
        binariesToUpdate.put(binary, immValue); // 记录需要更新的算术指令
    }

    // 交换二元指令的操作数
    private void swapOperands(RISCVbinary binary) {
        RISCVoperand temp = binary.getSrc1();
        binary.setSrcLeft(binary.getSrc2());
        binary.setSrcRight(temp);
    }

    // 更新二元指令：将add/addw/subw转换为立即数版本
    private void updateBinaryInstructions(Map<RISCVbinary, Integer> binariesToUpdate) {
        for (Map.Entry<RISCVbinary, Integer> entry : binariesToUpdate.entrySet()) {
            RISCVbinary binary = entry.getKey();
            int value = entry.getValue();
            String type = binary.getType();

            if ("add".equals(type)) {
                updateToAddi(binary, value);  // add -> addi
            }
            else if ("addw".equals(type)) {
                updateToAddiw(binary, value); // addw -> addiw
            }
            else if ("subw".equals(type)) {
                updateSubwToAddiw(binary, value); // subw -> addiw (负立即数)
            }
        }
    }

    // 更新为addi指令
    private void updateToAddi(RISCVbinary binary, int value) {
        binary.setType("addi");
        binary.setSrcRight(new RISCVimm(value, true));
    }

    // 更新为addiw指令
    private void updateToAddiw(RISCVbinary binary, int value) {
        binary.setType("addiw");
        binary.setSrcRight(new RISCVimm(value, true));
    }

    // 将subw转换为addiw（使用负立即数）
    private void updateSubwToAddiw(RISCVbinary binary, int value) {
        binary.setType("addiw");
        binary.setSrcRight(new RISCVimm(-value, true));
    }

    // 使用零寄存器优化
    private void changeReg2Zero() {
        for (RISCVblock block : blockInstr.keySet()) {
            List<RISCVinst> redundantInstructions = new ArrayList<>();

            LinkedList<RISCVinst> instructions = block.getInstructionlist();
            // 遍历指令序列（除最后一条）
            for (int i = 0; i < instructions.size() - 1; i++) {
                RISCVinst current = instructions.get(i);
                RISCVinst next = instructions.get(i + 1);

                // 处理零寄存器优化场景
                processZeroRegisterCase(current, next, redundantInstructions);
            }

            // 删除冗余指令
            removeInstructions(block, redundantInstructions);
        }
    }

    // 处理零寄存器优化场景
    private void processZeroRegisterCase(RISCVinst current, RISCVinst next,
                                         List<RISCVinst> redundantInstructions) {
        if (!(current instanceof RISCVmove moveInst)) return;

        // 情况1：加载零立即数
        if (moveInst.getSrc() instanceof RISCVimm immSrc && immSrc.getImm() == 0) {
            handleZeroImmediateCase(moveInst, next, redundantInstructions);
        }
        // 情况2：连续move指令
        else {
            handleRegisterMoveCase(moveInst, next, redundantInstructions);
        }
    }

    // 处理加载零立即数的情况
    private void handleZeroImmediateCase(RISCVmove moveInst, RISCVinst next,
                                         List<RISCVinst> redundantInstructions) {
        // 跳过特殊寄存器
        if (((physicalReg) moveInst.getDst()).isSReg()) return;

        // 如果后跟store指令且使用相同寄存器
        if (next instanceof RISCVstore store &&
                store.getSrc().equals(moveInst.getDst())) {
            // 将源寄存器替换为零寄存器
            store.setSrc(initReg.ZERO);
            redundantInstructions.add(moveInst); // 标记move指令为冗余
        }
    }

    // 处理连续move指令的情况
    private void handleRegisterMoveCase(RISCVmove moveInst, RISCVinst next,
                                        List<RISCVinst> redundantInstructions) {
        // 如果后跟move指令且目标寄存器相同
        if (next instanceof RISCVmove nextMove &&
                moveInst.getDst().equals(nextMove.getDst()) &&
                !nextMove.getDst().equals(nextMove.getSrc())) {
            redundantInstructions.add(moveInst); // 标记第一个move为冗余
        }
    }

    // 删除无用的加法指令
    private void deleteUselessAdd1() {
        for (RISCVblock block : blockInstr.keySet()) {
            List<RISCVinst> redundantInstructions = new ArrayList<>();
            List<RISCVbinary> binariesToReplace = new ArrayList<>();

            LinkedList<RISCVinst> instructions = block.getInstructionlist();
            for (int i = 0; i < instructions.size(); i++) {
                RISCVinst inst = instructions.get(i);

                // 处理加法指令（addi/addiw）
                if (inst instanceof RISCVbinary binary) {
                    processAddiInstruction(binary, binariesToReplace);
                }

                // 处理栈指针相关操作
                if (i < instructions.size() - 1) {
                    processStackPointerOperations(instructions.get(i),
                            instructions.get(i + 1),
                            redundantInstructions);
                }
            }

            // 删除冗余指令
            removeInstructions(block, redundantInstructions);
            // 替换加法指令为move指令
            replaceBinariesWithMoves(block, binariesToReplace);
        }
    }

    // 处理加法指令：源操作数为零的情况
    private void processAddiInstruction(RISCVbinary binary,
                                        List<RISCVbinary> binariesToReplace) {
        String type = binary.getType();
        // 只处理addi/addiw指令
        if (!("addi".equals(type) || "addiw".equals(type))) return;

        // 如果第二个源操作数是零立即数
        if (binary.getSrc2() instanceof RISCVimm imm && imm.getImm() == 0) {
            binariesToReplace.add(binary); // 标记为需要替换
        }
    }

    // 处理栈指针相关操作
    private void processStackPointerOperations(RISCVinst current, RISCVinst next,
                                               List<RISCVinst> redundantInstructions) {
        // 只处理addi指令且源寄存器为SP
        if (!(current instanceof RISCVbinary binary)) return;
        if (!"addi".equals(binary.getType())) return;
        if (!binary.getSrc1().equals(initReg.SP)) return;

        // 后跟load指令的情况
        if (next instanceof RISCVload load) {
            handleLoadAfterAdd(binary, load, redundantInstructions);
        }
        // 后跟store指令的情况
        else if (next instanceof RISCVstore store) {
            handleStoreAfterAdd(binary, store, redundantInstructions);
        }
    }

    // 处理load跟在add之后的情况
    private void handleLoadAfterAdd(RISCVbinary binary, RISCVload load,
                                    List<RISCVinst> redundantInstructions) {
        // 检查地址寄存器匹配且偏移量为零
        if (!binary.getDst().equals(load.getAddress())) return;
        if (!(load.getOffset() instanceof RISCVimm offset) || offset.getImm() != 0) return;

        // 优化：直接使用SP寄存器并设置偏移量
        load.setAddress(initReg.SP);
        load.setOffset(binary.getSrc2());
        redundantInstructions.add(binary); // 标记add指令为冗余
    }

    // 处理store跟在add之后的情况
    private void handleStoreAfterAdd(RISCVbinary binary, RISCVstore store,
                                     List<RISCVinst> redundantInstructions) {
        // 检查地址寄存器匹配且偏移量为零
        if (!binary.getDst().equals(store.getAddress())) return;
        if (!(store.getOffset() instanceof RISCVimm offset) || offset.getImm() != 0) return;

        // 优化：直接使用SP寄存器并设置偏移量
        store.setAddress(initReg.SP);
        store.setOffset(binary.getSrc2());
        redundantInstructions.add(binary); // 标记add指令为冗余
    }

    // 将二元指令替换为move指令
    private void replaceBinariesWithMoves(RISCVblock block, List<RISCVbinary> binaries) {
        for (RISCVbinary binary : binaries) {
            // 创建等效的move指令
            RISCVmove move = new RISCVmove(Arrays.asList(binary.getDst(), binary.getSrc1()));
            // 在原始指令后插入move指令
            block.insertAfter(binary, move);
            // 删除原始指令
            block.deleteInstr(binary);
        }
    }

    // 删除未使用的基本块
    private void deleteUnUsedBlock() {
        identifyJumpTargets();  // 识别跳转目标
        resolveJumpChains();    // 解析跳转链
        removeUnusedBlocks();   // 删除未使用块
    }

    // 识别跳转目标：收集直接跳转关系
    private void identifyJumpTargets() {
        for (RISCVfunction function : module.getFunctions()) {
            for (RISCVblock block : function.getBlocks()) {
                // 只处理单条跳转指令的块
                if (block.getInstructionlist().size() == 1) {
                    RISCVinst lastInst = block.getInstructionlist().getLast();
                    if (lastInst instanceof RISCVj jumpInst) {
                        tarBlock.put(block, jumpInst.getTarget());
                    }
                }
            }
        }
    }

    // 解析跳转链：找到最终跳转目标
    private void resolveJumpChains() {
        for (RISCVblock block : new HashSet<>(tarBlock.keySet())) {
            RISCVblock target = tarBlock.get(block);
            // 循环解析跳转链（A->B->C 变为 A->C）
            while (tarBlock.containsKey(target)) {
                target = tarBlock.get(target);
            }
            tarBlock.put(block, target);
        }
    }

    // 移除未使用的基本块
    private void removeUnusedBlocks() {
        for (RISCVfunction function : funcBlock.keySet()) {
            List<RISCVblock> redundantBlocks = new ArrayList<>();

            for (RISCVblock block : function.getBlocks()) {
                // 如果块在跳转映射中，标记为冗余
                if (tarBlock.containsKey(block)) {
                    redundantBlocks.add(block);
                    continue;
                }
                // 更新块内的跳转目标
                updateJumpTargets(block);
            }

            // 删除标记的冗余块
            removeBlocks(function, redundantBlocks);
        }
    }

    // 更新块内的跳转目标
    private void updateJumpTargets(RISCVblock block) {
        for (RISCVinst inst : block.getInstructionlist()) {
            // 更新直接跳转目标
            if (inst instanceof RISCVj jumpInst && tarBlock.containsKey(jumpInst.getTarget())) {
                jumpInst.setTarget(tarBlock.get(jumpInst.getTarget()));
            }
            // 更新条件跳转目标
            else if (inst instanceof RISCVbeqz branchInst && tarBlock.containsKey(branchInst.getTarget())) {
                branchInst.setTarget(tarBlock.get(branchInst.getTarget()));
            }
        }
    }

    // 重排基本块顺序以优化执行流
    private void reOrderBlock() {
        for (RISCVfunction function : funcBlock.keySet()) {
            LinkedList<RISCVblock> newOrder = new LinkedList<>();
            LinkedList<RISCVblock> oldBlocks = funcBlock.get(function);

            for (RISCVblock current : oldBlocks) {
                // 跳过已处理的块
                if (newOrder.contains(current)) continue;

                newOrder.add(current);
                RISCVinst lastInst = current.getInstructionlist().getLast();
                // 获取倒数第二条指令（如果存在）
                RISCVinst secondLastInst = getSecondLastInstruction(current);

                // 根据终止指令类型处理后续块
                processTerminalInstructions(current, lastInst, secondLastInst, newOrder);
            }

            // 设置新的块顺序
            function.setBlocks(newOrder);
        }
    }

    // 获取倒数第二条指令
    private RISCVinst getSecondLastInstruction(RISCVblock block) {
        int size = block.getInstructionlist().size();
        return size >= 2 ? block.getInstructionlist().get(size - 2) : null;
    }

    // 处理终止指令（跳转/分支）
    private void processTerminalInstructions(RISCVblock current, RISCVinst lastInst,
                                             RISCVinst secondLastInst,
                                             LinkedList<RISCVblock> newOrder) {
        // 处理直接跳转指令
        if (lastInst instanceof RISCVj jumpInst) {
            // 处理条件分支+跳转的组合
            if (secondLastInst instanceof RISCVbeqz branchInst) {
                handleBranchAndJump(current, branchInst, jumpInst, newOrder);
            }
            // 处理简单跳转
            else {
                handleSimpleJump(current, jumpInst, newOrder);
            }
        }
    }

    // 处理条件分支+跳转的组合
    private void handleBranchAndJump(RISCVblock current, RISCVbeqz branchInst,
                                     RISCVj jumpInst, LinkedList<RISCVblock> newOrder) {
        RISCVblock branchTarget = branchInst.getTarget();
        RISCVblock jumpTarget = jumpInst.getTarget();

        // 添加分支目标块（如果未处理且非当前块）
        if (!branchTarget.equals(current) && !newOrder.contains(branchTarget)) {
            newOrder.add(branchTarget);
        }

        // 添加跳转目标块（如果未处理且非当前块）
        if (!jumpTarget.equals(current) && !newOrder.contains(jumpTarget)) {
            newOrder.add(jumpTarget);
        }
    }

    // 处理简单跳转指令
    private void handleSimpleJump(RISCVblock current, RISCVj jumpInst,
                                  LinkedList<RISCVblock> newOrder) {
        RISCVblock target = jumpInst.getTarget();
        // 添加跳转目标块（如果未处理且非当前块）
        if (!target.equals(current) && !newOrder.contains(target)) {
            newOrder.add(target);
        }
    }

    // 窥孔优化：存储-加载对优化
    private void peepHole() {
        for (RISCVfunction function : module.getFunctions()) {
            for (RISCVblock block : function.getBlocks()) {
                optimizeStoreLoadPairs(block);  // 优化存储-加载对
                removeRedundantMoves(block);     // 删除冗余move指令
            }
        }
    }

    // 优化存储-加载对
    private void optimizeStoreLoadPairs(RISCVblock block) {
        List<RISCVinst> redundantLoads = new ArrayList<>();
        List<RISCVinst> movesToAdd = new ArrayList<>();

        LinkedList<RISCVinst> instructions = block.getInstructionlist();
        // 遍历指令序列（除最后一条）
        for (int i = 0; i < instructions.size() - 1; i++) {
            RISCVinst current = instructions.get(i);
            RISCVinst next = instructions.get(i + 1);

            // 检查是否为存储-加载对
            if (isStoreLoadPair(current, next)) {
                RISCVstore store = (RISCVstore) current;
                RISCVload load = (RISCVload) next;

                // 检查是否访问相同内存位置
                if (isSameMemoryAccess(store, load)) {
                    // 创建move指令替代加载
                    movesToAdd.add(createMoveForLoad(load, store));
                    redundantLoads.add(load); // 标记加载指令为冗余
                }
            }
        }

        // 插入move指令并删除冗余加载
        addMovesAfterLoads(block, movesToAdd, redundantLoads);
        removeInstructions(block, redundantLoads);
    }

    // 判断是否为存储-加载对
    private boolean isStoreLoadPair(RISCVinst current, RISCVinst next) {
        return current instanceof RISCVstore && next instanceof RISCVload;
    }

    // 检查是否访问相同内存位置
    private boolean isSameMemoryAccess(RISCVstore store, RISCVload load) {
        return store.getAddress().equals(load.getAddress()) &&
                ((RISCVimm) store.getOffset()).getImm() == ((RISCVimm) load.getOffset()).getImm();
    }

    // 创建替代加载的move指令
    private RISCVmove createMoveForLoad(RISCVload load, RISCVstore store) {
        return new RISCVmove(Arrays.asList(load.getDst(), store.getSrc()));
    }

    // 在加载指令后插入move指令
    private void addMovesAfterLoads(RISCVblock block, List<RISCVinst> moves,
                                    List<RISCVinst> loads) {
        for (int i = 0; i < loads.size(); i++) {
            block.insertAfter(loads.get(i), moves.get(i));
        }
    }

    // 删除目标与源相同的冗余move指令
    private void removeRedundantMoves(RISCVblock block) {
        block.getInstructionlist().removeIf(inst ->
                inst instanceof RISCVmove &&
                        ((RISCVmove) inst).getDst().equals(((RISCVmove) inst).getSrc()));
    }

    // 辅助方法：从块中删除指令列表
    private void removeInstructions(RISCVblock block, List<RISCVinst> instructions) {
        for (RISCVinst inst : instructions) {
            block.deleteInstr(inst);
        }
    }

    // 辅助方法：从函数中删除块列表
    private void removeBlocks(RISCVfunction function, List<RISCVblock> blocks) {
        for (RISCVblock block : blocks) {
            function.deleteBlock(block);
        }
    }
}